import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// 创建 axios 实例对象
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // 发送 cookie
  timeout: 60 * 1000 // request timeout
})

/**
 * 添加请求拦截器
 */
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log('请求错误：', error) // for debug
    return Promise.reject(error)
  }
)

/**
 * 添加响应拦截器
 */
service.interceptors.response.use(
  response => {
    const res = response.data
    if (response.config.responseType === 'blob' || response.config.responseType === 'arraybuffer'){
      return response
    }
    if (res.code !== 0) {
      Message({
        message: '响应拦截器：' + res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(res)
    } else {
      return res
    }
  },
  error => {
    console.log('请求响应错误：' + error) // for debug
    if (error.message.includes('timeout')) {
      Message({
        message: '请求服务器超时',
        type: 'error',
        duration: 5 * 1000
      })
    } else {
      Message({
        message: '响应拦截器2：' + error.message,
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }
)

export default service
